<?php

namespace common\components;

use Yii;

class Yuploader
{
	public $error;
	public function uploadToOss()
	{

	}

	public function submit($file)
	{
		if (!file_exists($file)) {
        	return $this->setError('文件不存在');
        }
        //获取文件类型
        $finfo = finfo_open(FILEINFO_MIME);
        $info = finfo_file($finfo, $file);
        finfo_close($finfo);
        $extension = explode(";", $info);
        $type = $extension[0];
        $obj = new CurlFile($file);
        $obj->setMimeType($type);	// 定义文件类型
        $post['file'] =  $obj;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);	//默认IPv4，PHP 5.3以上才可用
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_URL, Yii::$app->params['static_domain'] . 'upload');
		$return = curl_exec($ch);
        $info = curl_getinfo($ch);
        if (curl_errno($ch) || $info['http_code'] >= 300 || $info['http_code'] < 200 || $return == 'Fail' || $return == 'false') {
        	return $this->setError("[{$info['http_code']}]上传失败：" . $return);
        } else {
        	curl_close($ch);
        	return $return;
        }
	}

	private function setError($error)
	{
		$this->error = $error;
		return false;
	}
}